var COS = require('../../../utils/cos-wx-sdk-v5')

Page({
    data: {
        formData: {
            bookTitle: '',
            author: '',
            isbn: '',
            bookPress: '',
            category: '',
            price: '',
            brief: '',
            cover: ''
        },
        coverImage: '',
        isBookInfoFetched: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },

    onInputChange(e) {
        const field = e.currentTarget.dataset.name || e.currentTarget.targetDataset?.name || e.currentTarget.id || e.currentTarget.currentTarget?.dataset.name || e.target.dataset.name || e.target.id || e.currentTarget.name;
        const value = e.detail.value;
        console.log(field)
        console.log(value)
        this.setData({
            [`formData.${field}`]: value
        });
    },

    uploadImage() {
        wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            success: res => {
                const path = res.tempFiles[0].tempFilePath;
                this.setData({
                    coverImage: path
                });
            }
        });
    },

    submitForm() {
        const data = this.data.formData;

        if (!data.bookTitle) {
            wx.showToast({
                title: '书名不能为空',
                icon: 'none'
            });
            return;
        }
        if (!data.author) {
            wx.showToast({
                title: '作者不能为空',
                icon: 'none'
            });
            return;
        }
        if (!data.isbn) {
            wx.showToast({
                title: 'isbn号不能为空',
                icon: 'none'
            });
            return;
        }
        if (!/^(?:978|979)-?(?:[0-9]+-?){10}$/.test(data.isbn) && !/^?:(?:[0-9]+-?){9}[0-9X]$/.test(data.isbn)) {
            wx.showToast({
                title: 'isbn格式错误',
                icon: 'none'
            });
            return;
        }

        var filePath = this.data.coverImage
        // data.cover = filePath.substr(filePath.lastIndexOf('/') + 1);
        // this.data.formData.cover = filePath.substr(filePath.lastIndexOf('/') + 1);
        wx.request({
            url: 'http://localhost:8080/books/add',
            method: 'POST',
            data: {
                ...data,
            },
            success: res => {
                if (this.data.coverImage) {
                    this.downloadAndUpload(filePath);
                }
                console.log(res.data.msg)
                wx.showToast({
                    title: res.data.msg,
                    // icon: 'success'
                });
                // this.setData({
                //     formData: {},
                //     coverImage: ''
                // });
                //刷新当前页面
                // this.onLoad()
                // setTimeout(wx.navigateBack(), 3000)
                // setTimeout(() => wx.navigateBack(), 1000);
            },
            fail: () => {
                wx.showToast({
                    title: '提交失败，请稍后再试',
                    icon: 'none'
                });
            }
        });
    },

    uploadIng() {

        var cos = new COS({
            SecretId: 'AKIDtmUzHNGySikbMuGOM6f1B7qMeqpa9VdY',
            SecretKey: 'mJfnjQvDI9mESVK0VotkPr56vZ0EF4g4',
            SimpleUploadMethod: 'putObject',
        })

        var filePath = this.data.coverImage
        console.log("filePath：：")
        console.log(filePath)
        // var key = filePath.substr(filePath.lastIndexOf('/') + 1);
        console.log("cover::")
        console.log(this.data.formData.cover)
        cos.postObject({
            Bucket: 'ov-library-1316830564', //对象储存桶的名称
            Region: 'ap-guangzhou', //所属地域
            Key: 'bookCover/' + this.data.formData.isbn + '.jpg', // 存储在桶里的对象键
            FilePath: filePath,
        }, function (err, data) {
            if (err) {
                console.log('上传失败', err);
            } else {
                console.log('上传成功', data);
            }
        })
    },

    // 下载并上传网络图片
    downloadAndUpload(networkUrl) {
        const that = this;
        // 下载网络图片到本地临时路径（以微信小程序为例）
        wx.downloadFile({
            url: networkUrl,
            success(res) {
                if (res.statusCode === 200) {
                    const tempFilePath = res.tempFilePath;
                    that.setData({
                        coverImage: tempFilePath // 存储临时路径到data
                    }, () => {
                        that.uploadIng(); // 触发上传
                    });
                }
            },
            fail(err) {
                console.error('图片下载失败', err);
            }
        });
    },

    getBookInfo() {
        const data = this.data.formData;
        if (!/^(?:978|979)-?(?:[0-9]+-?){10}$/.test(data.isbn) &&
            !/^(?:[0-9]+-?){9}[0-9X]$/.test(data.isbn)) {
            wx.showToast({
                title: 'isbn格式错误',
                icon: 'none'
            });
            return;
        }

        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        setTimeout(() => {
            wx.hideLoading();
        }, 2000);

        wx.request({
            url: 'http://data.isbn.work/openApi/getInfoByIsbn?isbn=' + this.data.formData.isbn + '&appKey=' + 'd86f3a5735784b47bd43fd81b4ea013a',
            success: res => {
                console.log(res.data)
                if (res.data.code === 1) {
                    wx.showToast({
                        title: 'isbn格式错误',
                        icon: 'none'
                    });
                    return;
                }
                console.log(res.data)
                const book = res.data.data;
                this.setData({
                    formData: {
                        // bookTitle: book.bookName || '',
                        // author: book.author || '',
                        // isbn: book.isbn || '',
                        // bookPress: book.press || '',
                        // pressTime: book.pressDate || '',
                        bookTitle: book.bookName || '',
                        author: book.author || '',
                        isbn: book.isbn || '',
                        bookPress: book.press || '',
                        category: book.clcName || '',
                        price: Math.floor(book.price / 100) || '',
                        brief: book.bookDesc || '',
                        // cover: (JSON.parse(book.pictures)[0]) || ''
                    },
                    coverImage: (JSON.parse(book.pictures)[0]) || '',
                    // isBookInfoFetched: true,
                });
                this.submitForm();
            }
        })
    }

});